package ywpt.web.action.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import ywpt.components.acegi.domain.Resource;
import ywpt.core.exception.UniqueConstraintException;
import ywpt.core.util.StringTools;
import ywpt.core.web.BaseAction;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ecside.table.limit.Limit;
import org.ecside.util.RequestUtils;
import org.ecside.util.ServletUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import ywpt.service.system.ResourceService;

import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;

public class ResourceAction extends BaseAction implements ModelDriven<Resource>, Preparable {
	
	private static final long	serialVersionUID	= -5640556182831379089L;
	protected final Log			log					= LogFactory.getLog(ResourceAction.class);
	private List<Resource>		resourceList		= new ArrayList<Resource>();
	private ResourceService		resourceService;
	private String[]			toDelete;
	private String				roleId;
	private String				id;
	private Resource			resource;
	protected static int		DEFAULT_PAGE_SIZE	= 5;

	public ResourceAction() {
	}

	public void setResourceService(ResourceService resourceService) {
		this.resourceService = resourceService;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}


	public String getRoleId() {
		return roleId;
	}

	public void setRoleId(String roleId) {
		this.roleId = roleId;
	}

	public Resource getResource() {
		return resource;
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}

	public List<Resource> getResourceList() {
		return resourceList;
	}

	public void setResourceList(List<Resource> resourceList) {
		this.resourceList = resourceList;
	}

	public String[] getToDelete() {
		return toDelete;
	}

	public void setToDelete(String[] toDelete) {
		this.toDelete = toDelete;
	}


	@Override
	@SuppressWarnings("unchecked")
	public String execute() {
		resource = new Resource();
		return list();
	}

	/**
	 * 新增资源
	 * 
	 * @return
	 */
	public String input() {
		return INPUT;
	}

	/**
	 * 编辑资源
	 * 
	 * @return
	 */
	public String edit() {
		return INPUT;
	}

	/**
	 * 查看资源
	 * 
	 * @return
	 */
	public String view() {
		return "view";
	}
	
	public String save() {
		try {
			if (id == null) {
				resourceService.saveResource(resource);
			} else {
				resourceService.updateResource(resource);
			}
			this.addActionMessage("资源信息已保存!");
			return INPUT;
		} catch (UniqueConstraintException e) {
			if (e.getMessage().indexOf("资源名") != -1) {
				this.addFieldError("roleName", "资源名重复");
			} else {
				this.addActionError("保存错误:" + e.getMessage());
			}
			return INPUT;
		}
	}
	
	
	@SuppressWarnings("unchecked")
	public String list() {
		DetachedCriteria query = DetachedCriteria.forClass(Resource.class);
		if (!StringTools.isNullOrSpace(resource.getResName())) {
			query.add(Restrictions.like("resName", "%" + resource.getResName() + "%"));
		}
		if (!StringTools.isNullOrSpace(resource.getDescription())) {
			query.add(Restrictions.like("description", "%" + resource.getDescription() + "%"));
		}
		int totalRows = RequestUtils.getTotalRowsFromRequest(getRequest());
		if (totalRows < 0) {
			totalRows = resourceService.getResCountByCriteria(query);
		}
		int[] rowStartEnd = RequestUtils.getRowStartEnd(getRequest(), totalRows, DEFAULT_PAGE_SIZE, 0);
		Limit limit = RequestUtils.getLimit(getRequest(), "ec", totalRows, DEFAULT_PAGE_SIZE);
		// Sort sort = limit.getSort();
		// Map sortValueMap = sort.getSortValueMap();
		int pageSize = limit.getCurrentRowsDisplayed();
		query.setProjection(null);
		resourceList.addAll(resourceService.getResourcesByCriteria(query, pageSize, rowStartEnd[0]));
		return SUCCESS;
	}

	public String listResources() throws Exception {
		resourceList.addAll(resourceService.getResourcesByRole(roleId));
		return SUCCESS;
	}
	
	public String select() throws Exception {
		resourceList.addAll(resourceService.getResources());
		return SUCCESS;
	}
	
	public String delete() throws Exception {
		if (id != null) {
			resourceService.removeResource(id);
		}
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String deleteAjax() throws Exception {
		List<Map<String, String>> list = ServletUtils.getParameterMaps(getRequest());
		Long resIds[] = new Long[list.size()];
		int results[] = null;
		for (int i = 0; i < list.size(); i++) {
			Map<String, String> resMap = list.get(i);
			resIds[i] = Long.valueOf(resMap.get("recordKey"));
		}
		results = resourceService.removeResources(resIds);
		ServletUtils.defaultAjaxResopnse(list, results, getRequest(), getResponse());
		return NONE;
	}
	
	public Resource getModel() {
		return resource;
	}
	
	
	public void prepare() throws Exception {
		if (getId() != null) {
			this.resource = resourceService.getResourceById(new Long(getId()));
		}
	}
}